<template>
  <div class="app-container business-page">
    <div class="search-from">
      <el-form
        v-show="showSearch"
        id="searchFrom"
        :inline="true"
        :model="searchFrom"
        class="demo-form-inline"
      >
        <el-form-item>
          <el-input
            v-model.trim="searchFrom.keyword"
            clearable
            placeholder="请输入客户名称"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchFrom.status"
            clearable
            placeholder="商机阶段"
          >
            <el-option
              v-for="item in business_stage"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchFrom.resource"
            clearable
            placeholder="商机来源"
          >
            <el-option
              v-for="item in business_source"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-tree-select
            v-model="searchFrom.companyId"
            :data="companyOption"
            :disabled="useUserStore().userInfo.orgId != 484"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children'
            }"
            class="w-full"
            default-expand-all
            placeholder="请选择所属公司"
            @change="getDeptTree()"
          />
        </el-form-item>
        <el-form-item>
          <el-tree-select
            v-model="searchFrom.deptId"
            :data="deptIdOption"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children'
            }"
            class="w-full"
            placeholder="请选择所属部门"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchFrom.lastFollowTime"
            end-placeholder="最后跟进结束时间"
            range-separator="-"
            start-placeholder="最后跟进开始时间"
            style="width: 100%"
            type="daterange"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <!-- <el-form-item>
          <el-select
            v-model="searchFrom.projectType"
            clearable
            placeholder="项目类型"
          >
            <el-option
              v-for="item in project_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-button icon="Search" type="primary" @click="handleQuery"
            >查询</el-button
          >
          <el-button icon="Refresh" type="default" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button icon="Plus" type="primary" @click="addItem"
            >添加</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            :disabled="multiple"
            icon="Switch"
            plain
            type="primary"
            @click="toBusiness"
            >转移商机</el-button
          >
        </el-col> -->

        <!-- <el-button
              @click="addCollaboration"
              icon="Connection"
              plain
              type="primary"
              >添加协作</el-button
            > -->
        <el-col :span="1.5">
          <el-button
            :disabled="single"
            icon="Edit"
            plain
            type="primary"
            @click="editItem"
            >编辑商机</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            :disabled="single"
            icon="Delete"
            plain
            type="primary"
            @click="btnCheck('del')"
            >删除商机</el-button
          >
        </el-col>
        <!-- <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            icon="Upload"
            plain
            type="primary"
            @click="
              () => {
                uploadDia.open = true
                uploadDia.title = '导入商机'
                uploadDiaType = 'business'
              }
            "
            >导入商机</el-button
          >
        </el-col> -->
        <!-- <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            icon="Upload"
            plain
            type="primary"
            @click="
              () => {
                uploadDia.open = true
                uploadDia.title = '导入跟进'
                uploadDiaType = 'followUp'
              }
            "
            >导入跟进</el-button
          >
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            icon="Download"
            plain
            type="primary"
            @click="exportFn"
            >导出</el-button
          >
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList">
          <el-tooltip
            :content="'自定义列表'"
            class="item"
            effect="dark"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </right-toolbar>
      </el-row>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
      @row-dblclick="handleClickProject"
    >
      <el-table-column type="selection" width="45" />
      <!-- <el-table-column prop="titleName" label="商机标题" width="200">
        <template #default="scope">
          <div style="color: #1890ff">
            {{ scope.row.titleName ? scope.row.titleName : '--' }}
          </div>
        </template>
      </el-table-column> -->
      <!--        ....-->
      <el-table-column
        v-for="(item, index) in tableCol.filter(item => item.show)"
        :key="index"
        v-bind="item"
      >
        <template #default="scope">
          <div v-if="item.tooltip">
            <el-tooltip
              :content="item.tooltip(scope.row)"
              :disabled="!scope.row.invoiceMsg"
              effect="dark"
              placement="top"
            >
              {{ item.tooltipVal(scope.row) }}
            </el-tooltip>
          </div>
          <!-- <div v-if="scope.column.label == '项目类型'">
            <span>{{
              project_type.find(item1 => item1.value == scope.row.projectType)
                ? project_type.find(
                    item2 => item2.value == scope.row.projectType
                  ).label
                : '--'
            }}</span>
          </div> -->
          <!-- <div v-if="scope.column.label == '商机来源'">
            <span>{{
              business_source.find(item1 => item1.value == scope.row.resource)
                ? business_source.find(
                    item2 => item2.value == scope.row.resource
                  ).label
                : '--'
            }}</span>
          </div> -->
          <!-- <div v-if="scope.column.label == '客户类型'">
            <span>{{
              business_customer_type.find(
                item1 => item1.value == scope.row.customerGenre
              )
                ? business_customer_type.find(
                    item2 => item2.value == scope.row.customerGenre
                  ).label
                : '--'
            }}</span>
          </div> -->
          <!-- <div v-if="scope.column.label == '客户行业'">
            <span>{{
              industry_category.find(
                item1 => item1.value == scope.row.customerIndustry
              )
                ? industry_category.find(
                    item2 => item2.value == scope.row.customerIndustry
                  ).label
                : '--'
            }}</span>
          </div> -->
          <!-- <div v-if="scope.column.label == '状态'">
            <span
              v-if="scope.row.approvalStatus"
              class="text-12px text-#999999"
              >{{ scope.row.approvalStatus }}</span
            >
          </div> -->
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="scoped">
          <el-button
            icon="EditPen"
            plain
            size="small"
            type="primary"
            @click="toOrder(scoped.row)"
          >
            下单</el-button
          >
          <el-button
            icon="CircleCheck"
            plain
            size="small"
            type="success"
            @click="handleContinue(scoped.row)"
          >
            跟进</el-button
          >
          <!-- <el-button
            icon="CircleCheck"
            plain
            size="small"
            type="warning"
            @click="
              () => {
                router.push({
                  path: '/sales/contract/newContract',
                  query: {
                    t: 'business',
                    id: scoped.row.id,
                    c: scoped.row.customerName,
                    cI: scoped.row.customerId,
                    n: scoped.row.titleName
                  }
                })
              }
            "
            >添加合同</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      v-model:limit="searchFrom.pageSize"
      v-model:page="searchFrom.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 跟进 -->
    <FollowUp :dialogParam="followUpParam" @close="closeFn"></FollowUp>

    <!-- 自定义订单列表弹窗 -->
    <DiaFixTable
      v-model="diaTable.open"
      :dialogParam="diaTable"
      @ok="diaTableFn"
    />
  </div>
</template>

<script name="NicheList" setup>
import { reactive, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'

import {
  business_stage,
  business_source,
  project_type,
  popularize_type,
  business_customer_type,
  industry_category
} from '@/hooks/dict/business.js'
import { nicheList, saveNiche, nicheDetail, delNiche } from '@/api/nicheManage'
import FollowUp from '@/businessComponents/FollowUp'
import { getConfigKey } from '@/api/system/config'
import useUserStore from '@/store/modules/user'
import { initTable } from '@/utils/commo'
import {
  companyOption, //归属公司
  departmentOption,
  order_status //部门
} from '@/hooks/dict/order'
import { treeselect } from '@/api/rsgl/zzjg'
import { formatter } from 'element-plus'

// 本地列表配置
const SALESBUSINESSTABLE = [
  {
    show: true,
    prop: 'customerTaxcode',
    label: '税号',
    align: 'center',
    minWidth: 250
  },
  {
    show: true,
    prop: 'customerName',
    label: '客户名称',
    align: 'center',
    minWidth: 200,
    showOverflowTooltip: true
  },
  // {
  //   show: true,
  //   prop: 'customerGenre',
  //   label: '客户类型',
  //   align: 'center',
  //   minWidth: 200,
  //   showOverflowTooltip: true,
  //   formatter: row => {
  //     let label = proxy.selectDictLabel(
  //       business_customer_type.value,
  //       row.customerGenre
  //     )
  //     return label ? label : '--'
  //   }
  // },
  // {
  //   show: true,
  //   prop: 'customerIndustry',
  //   label: '客户行业',
  //   align: 'center',
  //   minWidth: 200,
  //   showOverflowTooltip: true,
  //   formatter: row => {
  //     let label = proxy.selectDictLabel(
  //       industry_category.value,
  //       row.customerIndustry
  //     )
  //     return label ? label : '--'
  //   }
  // },
  {
    show: true,
    prop: 'resource',
    label: '商机来源',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true,
    formatter: row => {
      let label = proxy.selectDictLabel(business_source.value, row.resource)
      return label ? label : '--'
    }
  },
  {
    show: true,
    prop: 'attnName',
    label: '联系人',
    align: 'center',
    minWidth: 100
  },
  // {
  //   show: true,
  //   prop: 'job',
  //   label: '职务',
  //   align: 'center',
  //   minWidth: 100
  // },
  {
    show: true,
    prop: 'attnPhone',
    label: '联系电话',
    align: 'center',
    minWidth: 100
  },
  {
    show: true,
    prop: 'belongName',
    label: '归属人员',
    align: 'center',
    minWidth: 100
  },
  {
    show: true,
    prop: 'popularizeTypeCode',
    label: '推广分类',
    align: 'center',
    minWidth: 200,
    showOverflowTooltip: true,
    formatter: row => {
      let label = proxy.selectDictLabel(
        popularize_type.value,
        row.popularizeTypeCode
      )

      return label ? label : '--'
    }
  },
  {
    show: true,
    prop: 'status',
    label: '商机状态',
    align: 'center',
    minWidth: 130,
    formatter: row => {
      let label = proxy.selectDictLabel(business_stage.value, row.status)
      return label ? label : '--'
    }
  },
  {
    show: true,
    prop: 'outflowName',
    label: '流失商机',
    align: 'center',
    minWidth: 130,
    showOverflowTooltip: true
  },
  {
    show: true,
    prop: 'projectDemand',
    label: '项目关键需求',
    align: 'center',
    minWidth: 110,
    showOverflowTooltip: true
  },
  // {
  //   show: true,
  //   prop: 'belongName',
  //   label: '负责人',
  //   align: 'center',
  //   minWidth: 100
  // },
  // {
  //   show: true,
  //   prop: 'projectType',
  //   label: '项目类型',
  //   align: 'center',
  //   minWidth: 100,
  //   showOverflowTooltip: true,
  // formatter: row => {
  //   let label = proxy.selectDictLabel(project_type.value, row.projectType)
  //   return label ? label : '--'
  // }
  // },
  {
    show: true,
    prop: 'followTime',
    label: '最后跟进',
    align: 'center',
    minWidth: 110,
    formatter: row => {
      return proxy.parseTime(row.followTime, '{y}-{m}-{d}')
    }
  },
  {
    show: true,
    prop: 'followNumber',
    label: '跟进次数',
    align: 'center',
    minWidth: 100
  },
  // {
  //   show: true,
  //   prop: 'companyName',
  //   label: '所属公司',
  //   align: 'center',
  //   minWidth: 110
  // },
  {
    show: true,
    prop: 'createTime',
    label: '录入时间',
    align: 'center',
    minWidth: 110
  },
  // {
  //   show: true,
  //   prop: 'approvalStatus',
  //   label: '状态',
  //   align: 'center',
  //   minWidth: 130
  // },
  {
    show: true,
    prop: 'dayNum',
    label: '未跟进天数',
    align: 'center',
    minWidth: 100
  }
]

const userStore = useUserStore()
const { proxy } = getCurrentInstance()
// 通用数据store
const router = useRouter()
const route = useRoute()
const data = reactive({
  loading: false,
  showSearch: true,
  searchFrom: {
    keyword: null, // 名称
    status: null, //商机阶段
    resource: null, //商机来源
    projectType: null, //项目类型
    // pageStyle: [10, 15, 20],
    lastFollowTime: [],
    companyId: useUserStore().userInfo.orgId,
    pageSize: 10,
    pageNum: 1
  },
  total: 0,
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  tableData: [],
  selectionList: [],
  followUpParam: {}, // 跟进弹窗配置
  uploadDiaType: null
})
const {
  loading,
  showSearch,
  searchFrom,
  tableData,
  selectionList,
  followUpParam,
  single,
  multiple,
  total,
  uploadDiaType
} = toRefs(data)
const deptIdOption = ref([])
// 获取部门树
const getDeptTree = () => {
  if (!searchFrom.value.companyId) return
  searchFrom.value.deptId = ''
  let data = { deptId: searchFrom.value.companyId }
  treeselect(data).then(res => {
    deptIdOption.value = res.data
  })
}
getDeptTree()
/** 搜索按钮操作 */
function handleQuery() {
  searchFrom.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  searchFrom.value = {
    pageNum: 1,
    pageSize: 10
  }
  getList()
}
//下单
const toOrder = row => {
  console.log('row', row)
  let type = null
  if (row.contactId != row.customerId) {
    type = 'customer'
  } else {
    type = 'cusLink'
  }
  console.log('type', type)
  let obj = {
    customerId: row.customerId,
    customerName: row.customerName,
    customerType: type
  }
  router.push({
    path: '/sales/indent/salesOrderForm',
    query: { salesOrderData: JSON.stringify(obj) }
  })
}
//打开跟进弹窗
function handleContinue(row) {
  /***订单模块 */
  console.log('row==>', row)
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'ord_small_medium'
  followUpParam.value.businessId = row.id //商机id
  followUpParam.value.customer = row.customerName //客户名称
  followUpParam.value.linkId = row.contactId //'联系人id'
  followUpParam.value.linkName = row.contactName //'联系人名称'
  followUpParam.value.status = row.status //商机状态
  followUpParam.value.principalId = userStore.userInfo.userId //默认提醒人id
  followUpParam.value.principalName = userStore.userInfo.nickName //默认提醒人name
  followUpParam.value.remindData = 7 //7天后提醒

  console.log('跟进==》', followUpParam.value)
}
// 组件关闭隐藏
const closeFn = row => {
  // 跟进
  followUpParam.value.isVisible = false
  getList()
}

//添加协作
function addCollaboration() {}
//新建商机
function addItem() {
  router.push({
    path: '/callCenter/smallClients/addNiche',
    query: { flag: 'add' }
  })
}
// 编辑、删除商机校验
const btnCheck = async val => {
  let res = await getConfigKey('small_medium_password')
  proxy
    .$prompt('输入验证码开启此功能', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      showCancelButton: false,
      inputType: 'password',
      closeOnClickModal: false
      // inputPattern: /^(?![^a-zA-Z]+$)(?!\D+$)(?![a-zA-Z0-9]+$).{8,16}$/,
      // inputErrorMessage: '请输入长度为8-16大小写字母及数字，特殊字符'
    })
    .then(({ value }) => {
      if (value !== res.msg) return proxy.$modal.msgError('密码错误')
      if (val == 'edit') {
        editItem()
      } else if (val == 'del') {
        delItem()
      }
    })
    .catch(() => {})
}
//编辑商机
function editItem() {
  if (!selectionList.value.length) {
    proxy.$modal.msgWarning('请选择要编辑的数据')
    return
  }
  if (selectionList.value.length > 1) {
    proxy.$modal.msgWarning('只能编辑一条数据')
    return
  }

  router.push({
    path: '/callCenter/smallClients/editNiche',
    query: { flag: 'update', id: selectionList.value[0].id }
  })
}
//删除
function delItem() {
  if (!selectionList.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal.confirm('是否确认删除选中的客户数据？').then(res => {
    let ids = selectionList.value
      .map(item => {
        return item.id
      })
      .join(',')
    delNiche(ids).then(res => {
      proxy.$modal.msgSuccess('删除成功！')
      getList()
    })
  })
}
//表格选择
function handleSelectionChange(selection) {
  selectionList.value = selection
  console.log('selectionList', selectionList)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
// 客户名称点击
const handleClickProject = row => {
  router.push({
    path: '/callCenter/smallClients/nicheDetails',
    query: { id: row.id }
  })
}
/**
 * 获取商机列表
 */
async function getList() {
  loading.value = true
  let param = { ...searchFrom.value }
  nicheList(param).then(res => {
    loading.value = false
    tableData.value = res.rows
    total.value = res.total
  })
}

const dialogParam = ref({})
//导出接口
const exportFn = () => {
  //
  let param = { ...searchFrom.value }
  delete param.pageNum
  delete param.pageSize
  proxy.downLoadByUrl('/ord/small/medium/export', param, '商机列表.xlsx')
}

/**** 自定义table 列表配置  2024/6/24 gbq */
let tableCol = ref(SALESBUSINESSTABLE)
/* ***
* 参数说明
* open: 打开自定义列表弹窗 true/false
tableName: 列表名称唯一值，用于保存列表配置和获取列表配置
tableCol: 列表列数据
initCol: 初始列表数据用于客户重置为本地的列表数据
*/
// 2. 设置传递的参数变量
const diaTable = ref({
  open: false,
  tableName: 'nicheTable', //唯一值防止与其他列表混合
  tableCol: tableCol.value,
  initCol: SALESBUSINESSTABLE
})

// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}
// 自定义列表
const handleTable = () => {
  diaTable.value.open = true
  diaTable.value.tableCol = tableCol.value
}
// 初始化
async function init() {
  // 初始化列表配置
  tableCol.value = initTable(diaTable.value.tableName, SALESBUSINESSTABLE)
  // 归属部门
  getList()
}
init()
</script>

<style lang="scss" scoped>
.business-page {
  display: block;
  .search-from {
    @apply pb-30px;
  }
  #searchFrom {
    :deep .el-input__wrapper {
      // width: 200px;
      @apply w-200px;
    }
    :deep .el-form-item {
      margin-right: 10px;
    }
  }
}
</style>
